package com.ruoyi.app.service.impl;

import java.math.BigDecimal;
import java.math.MathContext;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.app.domain.*;
import com.ruoyi.app.domain.vo.OrderInfoVo;
import com.ruoyi.app.domain.vo.RestockInfoVo;
import com.ruoyi.app.domain.vo.RestockProductVo;
import com.ruoyi.app.enums.OrderInfoGroupTypeEnum;
import com.ruoyi.app.enums.ProductInfoTypeEnum;
import com.ruoyi.app.service.*;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MybatisUtils;
import com.ruoyi.common.utils.OrderNumberUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.app.mapper.RestockInfoMapper;
import org.springframework.util.CollectionUtils;

/**
 * 进货单Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-12-12
 */
@Service
public class RestockInfoServiceImpl extends ServiceImpl<RestockInfoMapper, RestockInfo> implements IRestockInfoService
{
    @Autowired
    private RestockInfoMapper restockInfoMapper;

    @Autowired
    IProductInfoService productInfoService;

    @Autowired
    IRestockProductService restockProductService;

    @Autowired
    IShopSupplierService shopSupplierService;

    @Autowired
    IProductCategoryService productCategoryService;

    @Autowired
    IShopInfoService shopInfoService;

    /**
     * 查询进货单
     * 
     * @param id 进货单主键
     * @return 进货单
     */
    @Override
    public RestockInfoVo selectRestockInfoById(String id)
    {
//        return baseMapper.selectById(id);
        RestockInfo restockInfo = baseMapper.selectById(id);
        RestockInfoVo restockInfoVo = new RestockInfoVo();
        if(restockInfo == null || StringUtils.isBlank(restockInfo.getId())){
            return restockInfoVo;
        }
        BeanUtils.copyProperties(restockInfo, restockInfoVo);
        List<RestockProduct> restockProducts = restockProductService.listByRestockIds(Arrays.asList(restockInfo.getId()));
        if(!CollectionUtils.isEmpty(restockProducts)){
            restockInfoVo.setRestockProductVos(restockProducts.stream().map(item -> {
                RestockProductVo restockProductVo = new RestockProductVo();
                BeanUtils.copyProperties(item, restockProductVo);
                return restockProductVo;
            }).sorted(Comparator.comparing(RestockProductVo::getSort)).collect(Collectors.toList()));
        }
        return restockInfoVo;
    }

    /**
     * 查询进货单列表
     * 
     * @param restockInfoVo 进货单
     * @return 进货单
     */
    @Override
    public List<RestockInfoVo> selectRestockInfoList(RestockInfoVo restockInfoVo)
    {
//        return MybatisUtils.list(baseMapper, restockInfo);
        LambdaQueryWrapper<RestockInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>(restockInfoVo);
        lambdaQueryWrapper.orderByDesc(RestockInfo::getCreateTime);
        lambdaQueryWrapper.eq(RestockInfo::getShopId, restockInfoVo.getShopId());
        List<RestockInfo> orderInfos = baseMapper.selectList(lambdaQueryWrapper);
        if(CollectionUtils.isEmpty(orderInfos)){
            return new ArrayList<>();
        }
        HashSet<String> set = new HashSet<>();
        List<RestockInfoVo> restockInfoVos = orderInfos.stream().map(item -> {
            RestockInfoVo orderInfoVo1 = new RestockInfoVo();
            BeanUtils.copyProperties(item, orderInfoVo1);
            set.add(item.getId());
            return orderInfoVo1;
        }).collect(Collectors.toList());
        List<RestockProduct> restockProducts = restockProductService.listByRestockIds(set);
        if(CollectionUtils.isEmpty(restockProducts)){
            return restockInfoVos;
        }
        Map<String, List<RestockProductVo>> collect = restockProducts.stream().map(item -> {
            RestockProductVo restockProductVo = new RestockProductVo();
            BeanUtils.copyProperties(item, restockProductVo);
            return restockProductVo;
        }).collect(Collectors.groupingBy(RestockProduct::getRestockId));
        restockInfoVos.forEach(item ->{
            List<RestockProductVo> restockProductVos = collect.get(item.getId());
            if(!CollectionUtils.isEmpty(restockProductVos)){
                Collections.sort(restockProductVos, new Comparator<RestockProductVo>() {
                            @Override
                            public int compare(RestockProductVo p1, RestockProductVo p2) {
                                return p2.getSort() - p1.getSort();
                            }
                        });
                item.setRestockProductVos(restockProductVos);
            }

        });
        return restockInfoVos;
    }

    @Override
    public String add(RestockInfoVo restockInfoVo) {
        if (restockInfoVo == null) {
            throw new ServiceException("订单信息不嫩为空");
        }
        List<RestockProductVo> restockProductVos = restockInfoVo.getRestockProductVos();
        if (CollectionUtils.isEmpty(restockProductVos)) {
            throw new ServiceException("订单商品不能为空");
        }
        Set<String> productNames = restockProductVos.stream().filter(item -> StringUtils.isBlank(item.getProductId())).map(RestockProductVo::getProductName).collect(Collectors.toSet());
//        if(restockProductVos.size() != productNames.size()){
//            throw new ServiceException("商品名称不能重复");
//        }
        if(!CollectionUtils.isEmpty(productNames)){
            Boolean result = productInfoService.verification(restockInfoVo.getShopId(), productNames);
            if(!result){
                throw new ServiceException("商品已存在");
            }
        }
        restockInfoVo.setRestockNo(OrderNumberUtils.generateOrderNumber(6));
        if(StringUtils.isNotBlank(restockInfoVo.getSupplierId())){
            ShopSupplier shopSupplier = shopSupplierService.getById(restockInfoVo.getSupplierId());
            if(shopSupplier != null){
                restockInfoVo.setSupplierName(shopSupplier.getName());
            }
        }
//        restockInfoVo.setUpdateTime(DateUtils.getNowDate());
//        restockInfoVo.setCreateTime(DateUtils.getNowDate());
//        restockInfoMapper.insert(restockInfoVo);
        baseMapper.insert(restockInfoVo);
        //
        ArrayList<RestockProduct> restockProducts = new ArrayList<>();
        BigDecimal orderPurchasingPrice = new BigDecimal(0);
        Long totalNumber = 0L;
        int i = 1;
        for (RestockProductVo restockProductVo : restockProductVos){
            // 添加商品数量
            ProductInfo productInfo = new ProductInfo();
            if (StringUtils.isNotBlank(restockProductVo.getProductId())){
                if(restockProductVo.getPurchasingPrice() == null){
                    ProductInfo productInfo1 = productInfoService.selectProductInfoById(restockProductVo.getProductId());
                    restockProductVo.setPurchasingPrice(productInfo1.getPurchasingPrice());
                }
                productInfo.setId(restockProductVo.getProductId());
                productInfo.setTotalNumber(restockProductVo.getTotalNumber());
                productInfoService.addProductNumber(productInfo);
            } else {
                BeanUtils.copyProperties(restockProductVo, productInfo);
                productInfo.setShopId(restockInfoVo.getShopId());
                productInfo.setImg(restockProductVo.getProductImg());
                productInfo.setCode(restockProductVo.getProductCode());
                productInfo.setName(restockProductVo.getProductName());
                productInfo.setCategoryId(restockProductVo.getCategoryId());
                productInfo.setCategoryTxt(restockProductVo.getCategoryTxt());
                productInfo.setTotalNumber(restockProductVo.getTotalNumber());
                productInfo.setCurrentNumber(restockProductVo.getTotalNumber());
                productInfo.setPurchasingPrice(restockProductVo.getPurchasingPrice());
                productInfo.setSellingPrice(restockProductVo.getSellingPrice());
                productInfo.setType(ProductInfoTypeEnum.ORDER.getType());
                String productId = productInfoService.addOrUpdate(productInfo);
                restockProductVo.setProductId(productId);
            }
            BigDecimal purchasingPrice = restockProductVo.getPurchasingPrice();
            totalNumber += restockProductVo.getTotalNumber();
            if(purchasingPrice != null){
                BigDecimal multiply = purchasingPrice.multiply(new BigDecimal(restockProductVo.getTotalNumber()), MathContext.DECIMAL32);
                restockProductVo.setTotalPurchasingPrice(multiply);
                orderPurchasingPrice =  orderPurchasingPrice.add(multiply, MathContext.DECIMAL32);
            }
            restockProductVo.setShopId(restockInfoVo.getShopId());
            if(StringUtils.isNotBlank(restockProductVo.getCategoryId())){
                ProductCategory productCategory = productCategoryService.getById(restockProductVo.getCategoryId());
                if(productCategory != null){
                    restockProductVo.setCategoryTxt(productCategory.getCategoryName());
                }
            }
            restockProductVo.setRestockId(restockInfoVo.getId());
            restockProductVo.setRestockNo(restockInfoVo.getRestockNo());
            restockProductVo.setSort(i++);
            restockProducts.add(restockProductVo);
        }
        restockInfoVo.setTotalNumber(totalNumber);
        restockInfoVo.setTotalPrice(orderPurchasingPrice);
        restockProductService.saveBatch(restockProducts);
        baseMapper.updateById(restockInfoVo);
        return restockInfoVo.getId();
    }

    /**
     * 统计
     * @param restockInfoVo
     * @return
     */
    @Override
    public List<RestockInfoVo> statistics(RestockInfoVo restockInfoVo) {
        if(restockInfoVo == null || !OrderInfoGroupTypeEnum.isExistType(restockInfoVo.getGroupType())){
            throw new ServiceException("参数为空或类型不存在");
        }
        return baseMapper.statistics(restockInfoVo);
    }

    /**
     * 统计详情
     * @param restockInfoVo
     * @return
     */
    @Override
    public RestockInfoVo statisticsInfo(RestockInfoVo restockInfoVo) {
        if(restockInfoVo == null || restockInfoVo.getStartDate() == null || restockInfoVo.getEndDate() == null){
            throw new ServiceException("参数不能为空");
        }
        List<RestockProductVo> restockProductVos = baseMapper.statisticsCategoryList(restockInfoVo);
        RestockInfoVo infoVo = baseMapper.statisticsInfo(restockInfoVo);
        if(infoVo != null){
            infoVo.setRestockProductVos(restockProductVos);
        }
        return infoVo;
    }

    /**
     * 本月销售金额和数量
     * @param shopId
     * @return
     */
    @Override
    public RestockInfoVo currentMonthStatistics(String shopId) {
        if(StringUtils.isBlank(shopId)){
            return null;
        }
        return baseMapper.currentMonthStatistics(shopId);
    }
}
